<?php

   class Category extends Admin{
   	    
		private $categorysList;  //栏目列表
		
		private $info_model;  //模型数组
    	
		public function __construct(){
			parent::__construct();
			$this->categorysList = "";
			$this->info_model    = array();
			$info_model = DB::fetch_array("select *from `bb_info_model`");
			foreach($info_model as $val){
				$this->info_model[$val['mid']] = $val['name'];
			}
		}
		
		/*
		 * 栏目列表
		 */
		public function Index(){
           $this->mod = "Index";
		   $this->_getCategorysList(10,$this->_getCategorysByParent(0));
		   $this->_T['categorysList'] = $this->categorysList;
		   $this->template("parent");
		}
		
		/*
		 * 添加栏目（界面）
		 */
		public function Add(){
			$this->mod = "Add";
			$category = null;
			$categoryid = intval($_GET['categoryid']);
			if($categoryid)
			  $category = DB::fetch_row("select * from `bb_category` AS C left join 
			                            `bb_category_info` AS CI on C.categoryid=CI.categoryid where `C`.`categoryid`='{$categoryid}'");
			$this->_getTemplateGroups();
			if(is_array($category)){
				$this->_T['upCategory']['categoryid'] = $category['categoryid'];
				$this->_T['upCategory']['name'] = $category['name'];
				$this->_T['upCategory']['path'] = $category['path']."/";
			}else{
				$this->_T['upCategory']['categoryid'] = 0;
				$this->_T['upCategory']['name'] = "根目录";
				$this->_T['upCategory']['path'] = "";
			}
			$this->_T['models']  = DB::fetch_array("select *from `bb_info_model`");
			$this->_T['myOrder']     = "0";
			$this->_T['adminOrder']  = "id DESC";
			$this->_T['infoOrder']   = "newstime DESC";
			$this->_T['infoNum']     = "25";
			$this->template("parent");
		}
		
		/*
		 * 添加栏目（处理）
		 */
		public function Create(){
			$category = array();
			$category_info = array();
			$category_setting = array();
			$category['upid'] = $_POST['upid'];
			$category['mid']  = $_POST['mid'];
			$category['path']  = $_POST['path'];
			$category['path_state']  = "0";
			$category['to_url']  = "";
			$category['islast']  = $_POST['isLast']?"1":"0";
			$category['islist']  = "0";
			$category['path']  = $_POST['upCategoryPath'].$_POST['path'];
			$category['imgobjectid'] = "0";
			$category['openadd']  = $_POST['openAdd'];
			$category['hide']  = $_POST['isHidden']?"1":"0";
			$category['myorder']  = $_POST['myOrder'];
			$categoryId = DB::insert("bb_category", $category);
			$hgPath  = "Html/".$category['path']."/HeaderGroup";
			$fgPath  = "Html/".$category['path']."/FooterGroup";
			$cgPath  = "Html/".$category['path']."/CategoryGroup";
			$lgPath  = "Html/".$category['path']."/ListGroup";
			$igPath  = "Html/".$category['path']."/InfoGroup";
            
			File::createFolder($hgPath);  //创建文件夹
			File::createFolder($fgPath);
			File::createFolder($cgPath);
			File::createFolder($lgPath); 
			File::createFolder($igPath);
			
			$this->_createTempGroupFile($category['path']);
			
			if(!$categoryId)
				$this->showmessage("栏目创建失败,错误代号2","goback" ,2000, "返回");
			$category_info['categoryid'] = $categoryId;
			$category_info['name'] =  $_POST['name'];
			$category_info['bname'] =  $_POST['bname']?$_POST['bname']:$_POST['name'];
			$category_info['suffix'] = " ";
			$category_info['keywords'] = " ";
			$category_info['description'] = " ";
			$category_info['categorytext']  = " ";
			$category_info['lid']  = 0;
			$categoryInfoId = DB::insert("bb_category_info", $category_info);
			if(!$categoryInfoId)
				$this->showmessage("栏目创建失败,错误代号3","goback" ,2000, "返回");
			$category_setting['categoryid'] = $categoryId;
			$category_setting['header_groupid'] = $_POST['headerTempGroup'];
			$category_setting['footer_groupid'] = $_POST['footerTempGroup'];
			$category_setting['category_groupid'] = $_POST['categoryTempGroup'];
			$category_setting['list_groupid'] = $_POST['listTempGroup'];
			$category_setting['info_groupid'] = $_POST['infoTempGroup'];
			$category_setting['infonum'] = $_POST['infoNum'];
			$category_setting['adminorder'] = $_POST['adminOrder'];
			$category_setting['infoorder'] = $_POST['infoOrder'];
			$category_setting['sametitle'] = "1";
			$categorySettingId = DB::insert("bb_category_setting", $category_setting);
			if(!$categorySettingId)
				$this->showmessage("栏目创建失败,错误代号4","goback" ,2000, "返回");
			else
				$this->showmessage("栏目创建成功","?m=Admin/Category/Index" ,2000, "返回栏目列表");
		}
		
		/*
		 * 编辑栏目（界面）
		 */
		public function Edit(){
			$this->mod = "Edit";
			$categoryid = intval($_GET['categoryid']);
			$this->_T['categoryid'] = $categoryid;
			$upCategory = DB::fetch_row("select * from `bb_category` as C left join `bb_category` as UPC
			              on UPC.categoryid = C.upid left join `bb_category_info` as `UPCI` on UPCI.categoryid = UPC.categoryid 
			              where C.categoryid = '{$categoryid}'");
			$category = DB::fetch_row("select * from `bb_category` as C left join `bb_category_info` as CI on C.categoryid = CI.categoryid 
			                          left join `bb_category_setting` as CS on C.categoryid = CS.categoryid where C.categoryid='{$categoryid}'");
			$this->_T['category'] = $category;
			if($upCategory['categoryid']){
				$this->_T['upCategory']['categoryid']=$upCategory['categoryid'];
			    $this->_T['upCategory']['name']=$upCategory['name'];
			}else{
				$this->_T['upCategory']['categoryid']=0;
			    $this->_T['upCategory']['name']="根目录";
			}
			$this->_getTemplateGroups();
			$this->_T['models']  = DB::fetch_array("select *from `bb_info_model`");
			$this->template("parent");
		}
		
		/*
		 * 更新栏目（处理）
		 */
		public function Update(){
			$condition = array();
			$category = array();
			$category_info = array();
			$category_setting = array();
			$condition['categoryid'] = $_POST['categoryid'];
			$category['upid'] = $_POST['upid'];
			$category['mid']  = $_POST['mid'];
			$category['path']  = $_POST['path'];
			$category['path_state']  = "0";
			$category['to_url']  = "";
			$category['islast']  = $_POST['isLast']?"1":"0";
			$category['islist']  = "0";
			$category['path']  = $_POST['path'];
			$category['imgobjectid'] = "0";
			$category['openadd']  = $_POST['openAdd'];
			$category['hide']  = $_POST['isHidden']?"1":"0";
			$category['myorder']  = $_POST['myOrder'];
			if(!DB::update("bb_category", $category, $condition)){
				$this->showmessage("栏目更新失败,错误代号1","goback" ,2000, "返回");
			}
			$category_info['name'] =  $_POST['name'];
			$category_info['bname'] =  $_POST['bname']?$_POST['bname']:$_POST['name'];
			$category_info['suffix'] = " ";
			$category_info['keywords'] = " ";
			$category_info['description'] = " ";
			$category_info['categorytext']  = " ";
			$category_info['lid']  = 0;
			if(!DB::update("bb_category_info", $category_info, $condition)){
				$this->showmessage("栏目更新失败,错误代号2","goback" ,2000, "返回");
			}
			$category_setting['header_groupid'] = $_POST['headerTempGroup'];
			$category_setting['footer_groupid'] = $_POST['footerTempGroup'];
			$category_setting['category_groupid'] = $_POST['categoryTempGroup'];
			$category_setting['list_groupid'] = $_POST['listTempGroup'];
			$category_setting['info_groupid'] = $_POST['infoTempGroup'];
			$category_setting['infonum'] = $_POST['infoNum'];
			$category_setting['adminorder'] = $_POST['adminOrder'];
			$category_setting['infoorder'] = $_POST['infoOrder'];
			$category_setting['sametitle'] = "1";			
			if(!DB::update("bb_category_setting", $category_setting, $condition)){
				$this->showmessage("栏目更新失败,错误代号2","goback" ,2000, "返回");
			}
			
			$hgPath  = "Html/".$category['path']."/HeaderGroup";
			$fgPath  = "Html/".$category['path']."/FooterGroup";
			$cgPath  = "Html/".$category['path']."/CategoryGroup";
			$lgPath  = "Html/".$category['path']."/ListGroup";
			$igPath  = "Html/".$category['path']."/InfoGroup";
			
			File::deleteFile($hgPath, "delete files");
			File::deleteFile($fgPath, "delete files");
			File::deleteFile($cgPath, "delete files");
			File::deleteFile($lgPath, "delete files");
			File::deleteFile($igPath, "delete files");
			
			$this->_createTempGroupFile($category['path']);
			
			$this->showmessage("栏目更新成功","?m=Admin/Category/Index" ,2000, "返回栏目列表");
		}
        
		/*
		 * 删除栏目（处理）
		 */ 
		public function Delete(){
			$categoryid = intval($_GET['categoryid']);
			$category  = DB::fetch_row("select *from `bb_category` where `categoryid`='{$categoryid}'");
			$condition['categoryid'] = $categoryid;
			$deleted = false;
			if(!$category['islast']){
				$categorys = DB::fetch_array("select * from `bb_category` where `upid`='{$categoryid}'");
				if(!count($categorys))
					$deleted = true;
			}else{
				$deleted = true;
			}
			if($deleted){
				DB::delete("bb_category", $condition);
				DB::delete("bb_category_info", $condition);
				DB::delete("bb_category_setting", $condition);
				File::deleteFile("Html/".$category['path'], "delete dir");
				$this->showmessage("栏目删除成功","?m=Admin/Category/Index" ,2000, "返回栏目列表");
			}
			$this->showmessage("栏目删除失败，请先删除子栏目","goback" ,2000, "返回栏目列表");
		}
		
		private function _getCategorysByParent($upid){//获取父栏目
			$categorys = DB::fetch_array("select * from `bb_category` as C left join `bb_category_info` as CI 
			                             on C.categoryid = CI.categoryid where `upid` = '{$upid}' order by `myorder`");
			return $categorys;
		}
        
		private function _getCategorysList($padding,$upCategorys){//获取栏目列表
			if(!is_array($upCategorys)){
				return $upCategorys;
			}
			foreach($upCategorys as $key=>$category){
				$categorys = $this->_getCategorysByParent($category['categoryid']);
				$img = "";
				$ahref = "";
				$category_href = "";
				$info_model  = $this->info_model[$category['mid']];
				if($category['islast']){
					$img = "<img src='./App/view/Admin/images/file.gif'/>";
					$ahref="[<a href=\"?m=Admin/Info/{$info_model}/Index&categoryid={$category[categoryid]}\">信息列表</a>]";
					$ahref.="[<a href=\"?m=Admin/Info/{$info_model}/Add&categoryid={$category[categoryid]}\">添加信息</a>]";
					$ahref.= "[<a href=\"?m=Admin/Category/Edit&categoryid={$category[categoryid]}\">编辑</a>]";
					$ahref.= "[<a href=\"?m=Admin/Category/Delete&categoryid={$category[categoryid]}\">删除</a>]";
					$category_href="?m=Index/Info/InfoList&categoryid=".$category['categoryid'];
				}else{
					$img = "<img src='./App/view/Admin/images/folder.gif'/>";
					$ahref = "[<a href=\"?m=Admin/Category/Add&categoryid={$category[categoryid]}\">增加子栏目</a>]";
					$ahref.= "[<a href=\"?m=Admin/Category/EditTemp&categoryid={$category[categoryid]}\">模版编辑</a>]";
					$ahref.= "[<a href=\"?m=Admin/Category/Edit&categoryid={$category[categoryid]}\">编辑</a>]";
					$ahref.= "[<a href=\"?m=Admin/Category/Delete&categoryid={$category[categoryid]}\">删除</a>]";
					$category_href="?m=Index/Category&categoryid=".$category['categoryid'];
				}
				$this->categorysList.="<tr>";
				$this->categorysList.="<td><input type=\"text\" size=\"3\" name=\"myOrder[]\" value=\"{$category[myorder]}\"></td>";
				$this->categorysList.="<td>{$category[categoryid]}</td>";
				$this->categorysList.="<td style=\"padding-left:{$padding}px\">{$img}&nbsp;&nbsp;<a href=\"{$category_href}\" target=\"_blank\">{$category[name]}</a></td>";
				$this->categorysList.="<td>{$ahref}</td>";
				$this->categorysList.="</tr>";
				$this->_getCategorysList($padding+20, $categorys);
			}
		}
        
		/*
		 * 获取模版组
		 */
		private function _getTemplateGroups(){
			$groups = DB::fetch_array("select * from `bb_template_group` where `type`!='IndexGroup'");
			$headerGroups = array();
			$footerGroups = array();
			$listGroups   = array();
			$infoGroups   = array();
			$categoryGroups = array();
			foreach($groups as $val){
				switch($val['type']){
					case "HeaderGroup" :$headerGroups[]=$val;break;
					case "FooterGroup" :$footerGroups[]=$val;break;
					case "ListGroup"   :$listGroups[]=$val;break;
					case "InfoGroup"   :$infoGroups[]=$val;break;		
					case "CategoryGroup":$categoryGroups[]=$val;
				}
			}
			$this->_T['headerGroups']   = $headerGroups;
			$this->_T['footerGroups']   = $footerGroups;
			$this->_T['listGroups']     = $listGroups;
			$this->_T['infoGroups']     = $infoGroups;
			$this->_T['categoryGroups'] = $categoryGroups;
		}
		
		/*
		 * 创建模版组文件
		 */
		private function _createTempGroupFile($basePath){
			$hgPath  = "Html/".$basePath."/HeaderGroup";
			$fgPath  = "Html/".$basePath."/FooterGroup";
			$cgPath  = "Html/".$basePath."/CategoryGroup";
			$lgPath  = "Html/".$basePath."/ListGroup";
			$igPath  = "Html/".$basePath."/InfoGroup";
			$headerGroupid  = $_POST['headerTempGroup'];
			$footerGroupid  = $_POST['footerTempGroup'];
			$listGroupid    = $_POST['listTempGroup'];
			$infoGroupid    = $_POST['infoTempGroup'];
			$categoryGroupid= $_POST['categoryTempGroup'];	
			$block = DB::fetch_array("select *from `bb_block` as B left join `bb_block_template` as BT on B.`templateid`=BT.`templateid`
			               left join `bb_template_group` as TG on B.`groupid`=TG.`groupid` where B.`groupid`='{$headerGroupid}' 
			               or B.`groupid`='{$footerGroupid}' or B.`groupid`='{$listGroupid}' or B.`groupid`='{$infoGroupid}' 
			               or B.`groupid`='{$categoryGroupid}' ");		
			foreach($block as $val){
				$cssCon  =$val['css']?"<style type=\"text/css\">\n" .$val['css']."\n</style>\n":"";
				$jsCon   =$val['js']?"<script language=\"Javascript\" type=\"text/javascript\">\n" .$val['js']."\n</javascript>\n":"";
				$htmlCon =$val['content'];
				$con = $htmlCon.$cssCon.$jsCon;
				$fileName = "";
				switch($val['type']){
					case "HeaderGroup" :$fileName = $hgPath."/index".$val['terminalid'].".html";break;
					case "FooterGroup" :$fileName = $fgPath."/index".$val['terminalid'].".html";break;
					case "ListGroup"   :$fileName = $lgPath."/index".$val['terminalid'].".html";break;
					case "InfoGroup"   :$fileName = $igPath."/index".$val['terminalid'].".html";break;		
					case "CategoryGroup":$fileName = $cgPath."/index".$val['terminalid'].".html";
				}              
				if(!File::createText($fileName,$con)){
					$succeed = false;
				}
			}
		}
   }






?>